package com.timedomain.him.remake.ui;

import android.annotation.SuppressLint;
import android.app.AlertDialog;
import android.content.ComponentName;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.net.Uri;
import android.os.Build;
import android.os.Bundle;
import android.os.PowerManager;
import android.provider.Settings;
import android.support.annotation.NonNull;
import android.support.annotation.RequiresApi;
import android.text.TextUtils;
import android.util.AndroidRuntimeException;
import android.view.View;
import android.widget.EditText;

import com.timedomain.him.remake.R;
import com.timedomain.him.remake.utils.AppSettings;
import com.timedomain.him.remake.utils.BaseActivity;
import com.timedomain.him.remake.utils.HLog;

import org.jetbrains.annotations.Nullable;

import java.io.UnsupportedEncodingException;
import java.net.URLEncoder;
import java.nio.charset.StandardCharsets;


// 出处：https://blog.csdn.net/xiaoerbuyu1233/article/details/122130165


public class BackgroundActivateSettingsActivity extends BaseActivity {

    @Override
    protected void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_backgroundsetting);
        AppSettings.hasSeenBatteryOptimizationDialog = true;
        AppSettings.saveSettings(this);
    }

    public void openBatterySettings(View view) {
        try{
            Intent i = null;
            if (android.os.Build.VERSION.SDK_INT >= android.os.Build.VERSION_CODES.LOLLIPOP_MR1) {
                i = new Intent(Settings.ACTION_BATTERY_SAVER_SETTINGS);
                startActivity(i);
            }
            else{
                showToast("当前系统没有省电模式。");
            }

        }catch (Exception ex){
            showToast("打开设置失败");
        }
    }

    public void ignoreBatteryOptimization(View view) {
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {

            if(!FcfrtAppBhUtils.isIgnoringBatteryOptimizations(this)){
                FcfrtAppBhUtils.requestIgnoreBatteryOptimizations(this);
            }
            else{
                showToast("无需进行电池优化");
            }
        }
        else{
            showToast("当前系统无需进行电池优化。");
        }
    }

    public void openBackgroundSetting(View view) {
        try{
            FcfrtAppBhUtils.showOneKey(this);
        }catch (Exception ex){
            ex.printStackTrace();
            showToast("当前手机型号未知，请搜索相关教程然后手动设置");
        }
    }

    public void searchTutorials(View view) {
        final EditText input = new EditText(this);
        input.setHint("手机品牌/系统名称");
        new AlertDialog.Builder(this).setTitle("请输入手机型号：")
                .setView(input)
                .setNegativeButton("取消",null)
                .setPositiveButton("搜索", new DialogInterface.OnClickListener() {
                    @Override
                    public void onClick(DialogInterface dialog, int which) {
                        try {
                            if(input.getText().length() == 0){
                                input.setText("安卓手机");
                            }
                            String url = "https://www.baidu.com/s?wd="+ URLEncoder.encode(input.getText()+" 设置后台白名单", StandardCharsets.UTF_8.name());

                            Intent i = new Intent(Intent.ACTION_VIEW,Uri.parse(url));
                            startActivity(i);
                        } catch (UnsupportedEncodingException e) {
                            e.printStackTrace();
                        }
                    }
                }).create().show();
    }

    public void showAppSettings(View view) {
        try{
            Intent i = new Intent(Settings.ACTION_APPLICATION_DETAILS_SETTINGS);
            i.setData(android.net.Uri.parse("package:"+getPackageName()));
            startActivity(i);
        }catch (Exception ex){
            showToast("打开设置失败");
        }


    }


    public void openOverlay(View view) {
        if (android.os.Build.VERSION.SDK_INT >= android.os.Build.VERSION_CODES.M) {
            try {
                Intent i = new Intent(Settings.ACTION_MANAGE_OVERLAY_PERMISSION);
                i.setData(android.net.Uri.parse("package:" + getPackageName()));
                startActivity(i);
            } catch (Exception ex) {
                showToast("打开设置失败");
            }
        }else{
            showToast("不需要设置这个选项");
        }
    }
}

class FcfrtAppBhUtils {
    /**
     * 判断我们的应用是否在白名单中
     * @param context
     * @return
     */
    @RequiresApi(api = Build.VERSION_CODES.M)
    public static boolean isIgnoringBatteryOptimizations(Context context) {
        boolean isIgnoring = false;
        PowerManager powerManager = (PowerManager) context.getSystemService(Context.POWER_SERVICE);
        if (powerManager != null) {
            isIgnoring = powerManager.isIgnoringBatteryOptimizations(context.getPackageName());
        }
        return isIgnoring;
    }

    /**
     * 申请加入白名单
     * @param context
     */
    @RequiresApi(api = Build.VERSION_CODES.M)
    public static void requestIgnoreBatteryOptimizations(Context context) {
        try {
            @SuppressLint("BatteryLife") Intent intent = new Intent(Settings.ACTION_REQUEST_IGNORE_BATTERY_OPTIMIZATIONS);
            intent.setData(Uri.parse("package:" + context.getPackageName()));
            context.startActivity(intent);
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    /**
     * 跳转到指定应用的首页
     */
    private static void showActivity(Context context,@NonNull String packageName) {
        Intent intent = context.getPackageManager().getLaunchIntentForPackage(packageName);
        context.startActivity(intent);
    }

    /**
     * 跳转到指定应用的指定页面
     */
    private static void showActivity(Context context,@NonNull String packageName, @NonNull String activityDir) {
        Intent intent = new Intent();
        intent.setComponent(new ComponentName(packageName, activityDir));
        intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
        context.startActivity(intent);
    }

    public static void showOneKey(Context context){
        HLog.d("FcfrtAppBhUtils", "Mobile brand: "+Build.BRAND);
        if(isHuawei()){
            goHuaweiSetting(context);
            return;
        }
        if(isXiaomi()){
            goXiaomiSetting(context);
            return;
        }
        if(isOPPO()){
            goOPPOSetting(context);
            return;
        }
        if(isVIVO()){
            goVIVOSetting(context);
            return;
        }
        if(isMeizu()){
            goMeizuSetting(context);
            return;
        }
        if(isSamsung()){
            goSmartisanSetting(context);
            return;
        }
        if(isLeTV()){
            goLetvSetting(context);
            return;
        }
        if(isSmartisan()){
            goSmartisanSetting(context);
            return;
        }
        throw new AndroidRuntimeException(new IllegalStateException("不支持的型号"));
    }

    /**
     * 华为厂商判断
     * @return
     */
    public static boolean isHuawei() {
        if (Build.BRAND == null) {
            return false;
        } else {
            return Build.BRAND.toLowerCase().contains("huawei") || Build.BRAND.toLowerCase().contains("honor");
        }
    }

    /**
     * 小米厂商判断
     * @return
     */
    public static boolean isXiaomi() {
        return Build.BRAND != null && Build.BRAND.toLowerCase().contains("xiaomi");
    }
    /**
     * OPPO厂商判断
     * @return
     */
    public static boolean isOPPO() {
        return Build.BRAND != null && Build.BRAND.toLowerCase().contains("oppo");
    }
    /**
     * VIVO厂商判断
     * @return
     */
    public static boolean isVIVO() {
        return Build.BRAND != null && Build.BRAND.toLowerCase().contains("vivo");
    }

    public static boolean isMeizu() {
        return Build.BRAND != null && Build.BRAND.toLowerCase().contains("meizu");
    }
    public static boolean isSamsung() {
        return Build.BRAND != null && Build.BRAND.toLowerCase().contains("samsung");
    }
    public static boolean isLeTV() {
        return Build.BRAND != null && Build.BRAND.toLowerCase().contains("letv");
    }
    public static boolean isSmartisan() {
        return Build.BRAND != null && Build.BRAND.toLowerCase().contains("smartisan");
    }

    /**
     * 跳转华为手机管家的启动管理页
     * 操作步骤：应用启动管理 -> 关闭应用开关 -> 打开允许自启动
     * @param context
     */
    public static void goHuaweiSetting(Context context) {
        try {
            showActivity(context,"com.huawei.systemmanager",
                    "com.huawei.systemmanager.startupmgr.ui.StartupNormalAppListActivity");
        } catch (Exception e) {
            try{
                showActivity(context,"com.huawei.systemmanager",
                        "com.huawei.systemmanager.optimize.bootstart.BootStartActivity");
            }catch (Exception ex){
                showActivity(context,"com.huawei.systemmanager");
            }

        }
    }

    /**
     * 跳转小米安全中心的自启动管理页面
     * 操作步骤：授权管理 -> 自启动管理 -> 允许应用自启动
     * @param context
     */
    public static void goXiaomiSetting(Context context) {
        showActivity(context,"com.miui.securitycenter",
                "com.miui.permcenter.autostart.AutoStartManagementActivity");
    }

    /**
     * 跳转 OPPO 手机管家
     * 操作步骤：权限隐私 -> 自启动管理 -> 允许应用自启动
     * @param context
     */
    public static void goOPPOSetting(Context context) {
        try {
            showActivity(context,"com.coloros.phonemanager");
        } catch (Exception e1) {
            try {
                showActivity(context,"com.oppo.safe");
            } catch (Exception e2) {
                try {
                    showActivity(context,"com.coloros.oppoguardelf");
                } catch (Exception e3) {
                    showActivity(context,"com.coloros.safecenter");
                }
            }
        }
    }

    /**
     * 跳转 VIVO 手机管家
     * 操作步骤：权限管理 -> 自启动 -> 允许应用自启动
     * @param context
     */
    public static void goVIVOSetting(Context context) {
        showActivity(context,"com.iqoo.secure");
    }

    /**
     * 跳转魅族手机管家
     * 操作步骤：权限管理 -> 后台管理 -> 点击应用 -> 允许后台运行
     * @param context
     */
    public static void goMeizuSetting(Context context) {
        showActivity(context,"com.meizu.safe");
    }

    /**
     * 跳转三星智能管理器
     * 操作步骤：自动运行应用程序 -> 打开应用开关 -> 电池管理 -> 未监视的应用程序 -> 添加应用
     * @param context
     */
    public static void goSamsungSetting(Context context) {
        try {
            showActivity(context,"com.samsung.android.sm_cn");
        } catch (Exception e) {
            showActivity(context,"com.samsung.android.sm");
        }
    }

    /**
     *跳转乐视手机管家
     * 操作步骤：自启动管理 -> 允许应用自启动
     * @param context
     */
    public static void goLetvSetting(Context context) {
        showActivity(context,"com.letv.android.letvsafe",
                "com.letv.android.letvsafe.AutobootManageActivity");
    }

    public static void goSmartisanSetting(Context context) {
        showActivity(context,"com.smartisanos.security");
    }

}